//
//  MeirongViewController.m
//  减肥,美容老中医偏方
//
//  Created by Appying on 14-9-17.
//  Copyright (c) 2014年 陈朕. All rights reserved.
//

#import "MeirongViewController.h"

@interface MeirongViewController ()

@end

@implementation MeirongViewController
@synthesize cell;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        
        UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, boundswidth-120, 44)];
        navLabel.text = @"美容偏方";
        navLabel.textColor = [UIColor whiteColor];
        navLabel.font = [UIFont systemFontOfSize:18];
        navLabel.textAlignment = NSTextAlignmentCenter;
        self.navigationItem.titleView = navLabel;

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    meirongArray = [[NSMutableArray alloc]init];
    
    [self httpRquestLoadData];
    
    meirongTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, boundswidth, boundsheight)];
    meirongTableView.delegate = self;
    meirongTableView.dataSource = self;
    [self setExtraCellLineHidden:meirongTableView];
    meirongTableView.separatorStyle = UITableViewCellAccessoryNone;
    [meirongTableView registerClass:[AppTableViewCell class] forCellReuseIdentifier:@"TableSampleIdentifierCell"];
    [self.view addSubview:meirongTableView];
    [self setupRefresh];
    
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [meirongTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//#warning 自动刷新(一进入程序就下拉刷新)
    [meirongTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [meirongTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    meirongTableView.headerPullToRefreshText = @"下拉可以刷新了";
    meirongTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    meirongTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    meirongTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    meirongTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    meirongTableView.footerRefreshingText = @"正在帮你加载中,不客气";
}
#pragma mark 开始进入刷新状态  0初始化Data 1 分页Data
- (void)headerRereshing
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self httpRquestLoadData];
        
    });
    
    
}

- (void)footerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        start = end;
        end = end+10;
        [self pageLoadData];
    });
    
}

-(void)httpRquestLoadData{
    [meirongArray removeAllObjects];
    [meirongTableView reloadData];
    start = 0;
    end = 20;
    NSString *url = [NSString stringWithFormat:@"%@cid=2&start=%d&count=%d",HTTPURL,start,end];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request setDelegate:self];
    request.timeOutSeconds = 6;
    [request startAsynchronous];
    
}
-(void)pageLoadData{
    start = 20;
    end = 30;
    NSString *url = [NSString stringWithFormat:@"%@cid=2&start=%d&count=%d",HTTPURL,start,end];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request setDelegate:self];
    request.timeOutSeconds = 6;
    [request startAsynchronous];
}

#pragma mark ASIHTTPRequest
-(void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"网络稍慢或服务器请求异常,请稍后再试~^_^" duration:2];
    [meirongTableView headerEndRefreshing];
    [meirongTableView footerEndRefreshing];
}
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSString *str =  [request responseString];
    SBJsonParser *jsonParser = [[SBJsonParser alloc]init];
    _dir =  [jsonParser objectWithString:str];
    NSArray *array = [_dir objectForKey:@"data"];
    for (int i = 0; i < array.count; i++) {
        appBean = [array objectAtIndex:i];
        [meirongArray addObject:appBean];
        [meirongTableView reloadData];
    }
    [meirongTableView headerEndRefreshing];
    [meirongTableView footerEndRefreshing];
}
#pragma mark UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return meirongArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [tableView deselectRowAtIndexPath:indexPath animated:NO];
    appBean = [AppBean shareInstence];
    _dir = [meirongArray objectAtIndex:indexPath.row];
    [appBean setUrl:[_dir objectForKey:@"url"]];
    [appBean setTitle:[_dir objectForKey:@"title"]];
    AppHtmlViewController *htmlController = [[AppHtmlViewController alloc]init];
    [self.navigationController pushViewController:htmlController animated:YES];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *TableSampleIdentifier = @"TableSampleIdentifierCell";
    cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        
        cell = [[AppTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier];
    }
    else{  //重要，释放cell,防止闪退方法，其他CustomCell 均可沿用
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    _dir = [meirongArray objectAtIndex:indexPath.row];
    cell.title.text = [_dir objectForKey:@"title"];
    return cell;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
